<template>
  <div>
    <div v-if="isViewMode" class="report-action">
      <el-button type="primary" :loading="printLoading" @click="printPage">
        <i class="fa fa-print"></i>
        打印
      </el-button>
      <el-button
        icon="el-icon-download"
        type="primary"
        :loading="printLoading"
        @click="exportToExcel"
      >
        导出
      </el-button>
    </div>
    <div v-loading="loading" class="report-wrap">
      <div :id="printId">
        <div class="report-main">
          <table class="table">
            <tbody>
              <tr>
                <td class="border-0" colspan="10" data-font='{"sz": 16, "bold": true}'>
                  <h3 class="report-title">{{ fileName }}</h3>
                </td>
              </tr>
              <tr>
                <!-- <td class="border-0 font-weight-bold d-flex justify-content-end p-0"
                    colspan="10">
                  <span style="max-width: 24rem">档案卡编号： -</span>
                </td> -->
              </tr>
            </tbody>
          </table>
          <industry-info-view
            :related="latestRelatedView"
            :orgCorp="shareholderCorp"
            :queryId="queryId"
            @save="judgeGetData"
            :view-mode="isViewMode"
          ></industry-info-view>
          <customer-industrial :queryId="queryId" :view-mode="isViewMode"></customer-industrial>
          <house-hold-view :queryId="queryId" :view-mode="isViewMode"></house-hold-view>
          <share-holder-view
            :shareholders="shareholders"
            v-if="!isIndividual"
            :queryId="queryId"
            @success="getShareHolder"
            :view-mode="isViewMode"
          ></share-holder-view>
          <customer-finance-source
            :queryId="queryId"
            :view-mode="isViewMode"
          ></customer-finance-source>
          <customer-insurance-order
            :queryId="queryId"
            :view-mode="isViewMode"
          ></customer-insurance-order>
        </div>
      </div>
    </div>
    <div class="text-center" v-if="!isViewMode">
      <el-button type="primary" v-if="projectStatus === 0" :loading="saveLoading" @click="saveData">
        完成档案卡
      </el-button>
    </div>
  </div>
</template>

<script>
import {
  printPage,
  exportToExcel,
  getResultData,
  getResultArray,
} from '@/gov/components/creditFile/index'
import IndustryInfoView from '@/gov/views/files/IndustryInfoView'
import CustomerIndustrial from '@/gov/components/creditFile/CustomerIndustrial'
import HouseHoldView from '@/gov/components/creditFile/HouseHoldView'
import ShareHolderView from '@/gov/components/creditFile/ShareHolderView'
import CustomerFinanceSource from '@/gov/components/creditFile/CustomerFinanceSource'
import CustomerInsuranceOrder from '@/gov/components/creditFile/CustomerInsuranceOrder'
import { mapGetters } from 'vuex'
export default {
  components: {
    IndustryInfoView,
    CustomerIndustrial,
    HouseHoldView,
    ShareHolderView,
    CustomerFinanceSource,
    CustomerInsuranceOrder,
  },
  props: {
    queryId: {
      type: String,
      default: '',
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      saveLoading: false,
      printLoading: false,
      loading: false,
      latestRelatedView: {},
      tableName: 'project_white_list',
      // 法人信息 股东信息 放入模块需请求两次
      shareholderCorp: {},
      shareholders: [],
    }
  },
  computed: {
    ...mapGetters(['user']),
    isUserTown() {
      return +this.user.orgRegionLever === 4 || +this.user.orgRegionLever === 3
    },
    printId() {
      return `gov_crdit_${this.queryId}`
    },
    // 档案卡状态
    projectStatus() {
      // 0 未调查 1 已完成
      return +this.latestRelatedView.project_status
    },
    fileName() {
      return `${this.latestRelatedView.customer_name || ''}数字档案卡`
    },

    isViewMode() {
      //  || this.projectStatus === 1
      // || !this.isUserTown
      return this.viewMode
    },
    isIndividual() {
      return ['org_individual', 'org_large_breed', 'org_farm'].includes(
        this.latestRelatedView.org_class
      )
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (!this.queryId) {
          return
        }
        this.getData()
        this.getShareHolder()
      },
      immediate: true,
    },
  },
  mounted() {},
  created() {},
  methods: {
    saveData() {
      const data = {
        project_status: 1,
      }
      if (+this.latestRelatedView.project_status === 0) {
        data.archive_complete_time = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
      }
      this.$utils
        .msgbox({
          message: '是否完成档案卡？',
          type: 'warning',
          beforeClose: () => this.updateRelated(data),
        })
        .then(res => {
          this.$message.success('档案卡已完成')
          this.$emit('success', res)
          this.getData()
        })
        .catch(() => this.$message.error(`提交失败，请重试！`))
    },
    updateRelated(data) {
      return new Promise((resolve, reject) => {
        this.$api
          .updateData(this.$serviceName, 'project_white_list', this.queryId, data)
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    judgeGetData(val) {
      // val = false 修改法人 true 修改基本信息
      if (val) {
        this.getData(false)
      } else {
        this.getShareHolder(false)
      }
    },
    async getShareHolder(isloading = true) {
      this.shareholderCorp = {}
      this.shareholders = []
      this.loading = isloading
      const params = {
        'customer_related_id.eq': this.queryId,
      }
      await this.$api
        .getData(this.$serviceName, 'datum_customer_shareholder_view', params, { sh_rate: 'desc' })
        .then(res => {
          const data = getResultArray(res)
          for (const sh of data) {
            if (+sh.is_corp === 1) {
              this.shareholderCorp = { ...sh }
              if (+this.shareholderCorp.marriage_status === 0) {
                this.shareholderCorp.marriage_status = '2'
              }
            } else {
              // 如果sh_rate为字符串则页面显示不出来
              if (+sh.sh_rate > 0) {
                this.shareholders.push({ ...sh })
              }
            }
          }
        })
      this.loading = false
    },
    async getData(isloading = true) {
      this.loading = isloading
      const params = {
        'project_white_list_id.eq': this.queryId,
      }
      await this.$api
        .getData(this.$serviceName, this.tableName, params, { create_time: 'desc' })
        .then(res => {
          this.latestRelatedView = getResultData(res)
        })
        .catch(() => {
          this.$message.error('请求项目基本信息失败')
        })
      this.loading = false
    },
    printPage() {
      printPage(this.printId)
    },
    exportToExcel() {
      this.printLoading = true
      exportToExcel(this.printId, this.fileName)
        .catch(err => {
          const msg = (err && err.message) || ''
          this.$message.error(`导出失败，请重试！${msg}`)
        })
        .finally(() => {
          this.printLoading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/gov/components/creditFile/style.scss';
</style>
